﻿using System;
using System.Text;
using System.Security.Cryptography;

namespace gms.security {
	public static class Hashing {
		public static byte[] encrypt(string input) {
			SHA512Managed ncrypt0r = new SHA512Managed();

			return ncrypt0r.ComputeHash(Encoding.UTF8.GetBytes(input));
		}
		public static byte[] encrypt(byte[] input) {
			SHA512Managed ncrypt0r = new SHA512Managed();

			return ncrypt0r.ComputeHash(input);
		}
		public static byte[] generate_salt(int min = 16, int max = 32) {
			Random ran = new Random();
			int size = ran.Next(min, max);

			byte[] retval = new byte[32];

			RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

			rng.GetNonZeroBytes(retval);

			return retval;
		}
		public static byte[] combine_bytes(params object[] byte_arrays) {
			int total_bytes = 0;
			int current_byte = 0;
			byte[] local;
			byte[] retval;

			for (int i = 0; i < byte_arrays.Length; i++) {
				local = (byte[])byte_arrays[i];

				total_bytes += local.Length;
			}

			retval = new byte[total_bytes];

			for (int i = 0; i < byte_arrays.Length; i++) {
				local = (byte[])byte_arrays[i];

				for (int j = 0; j < local.Length; j++) {
					retval[current_byte++] = local[j];
				}
			}

			return retval;
		}
		public static bool bytes_are_same(byte[] first, byte[] second) {
			bool retval = true;

			if (first.Length != second.Length) {
				retval = false;
			}
			else {
				for (int i = 0; i < first.Length; i++) {
					if (first[i] != second[i]) {
						retval = false;
					}
				}
			}			

			return retval;
		}
		public static byte[] get_password_hash(string pass, byte[] salt) {
			return encrypt(combine_bytes(encrypt(pass), salt));
		}
	}
}